﻿using Enum;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Practice.API.Application.Commands.Main;
using Practice.API.Application.Commands.Permissionw;
using Practice.API.Application.Commands.Roles;
using Practice.API.Application.Commands.UserW;
using Practice.API.Common;
using Practice.Common.Domains;
using Practice.Common.Dto;
using Practice.Common.Infrastructure.Interfaces;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Practice.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    /*[Authorize]*/
    public class PerController : ControllerBase
    {
        public readonly IMediator mediator;
        public readonly IConfiguration _configuration;
        public readonly IIdentityService identityService;

        public PerController(IMediator mediator, IConfiguration configuration, IIdentityService identityService)
        {
            this.mediator = mediator;
            _configuration = configuration;
            this.identityService = identityService;
        }




        /// <summary>
        /// 添加权限
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        /// 
        [HttpPost("AddPermission")]
        public async Task<Result> AddUser(PermissionCreateCommand cmd)
        {
            return await mediator.Send(cmd);
        }
        /// <summary>
        /// 权限列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("GetPermissionList")]

        public async Task<Result> html(PermissionListCommand request)
        {
            var result = await mediator.Send(request);
            return result;
        }


        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="Pwd"></param>
        /// <returns></returns>


        /// <summary>
        /// 生成 JWT Token（令牌）
        /// </summary>
        /// <returns></returns>
        private string CreateTokenString(string UserName)
        {
            //读取配置文件
            var jwtSettings = _configuration.GetSection("JWT").Get<JwtSettings>();
            //私钥
            var secretByte = Encoding.UTF8.GetBytes(jwtSettings.SecurityKey);
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            //Claims是指用户的身份信息，例如用户名、角色、权限等，它们通常被包含在一个ClaimsPrincipal对象中。
            var claims = new[]
            {
         new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
         new Claim("Email","pmandy@163.com"),
         new Claim("Phone","123456"),
         new Claim("UserId","1"),
         new Claim("UserName",UserName),
     };

            // 生成Token
            var token = new JwtSecurityToken(
                issuer: jwtSettings.Issuer,//发行者
                audience: jwtSettings.Audience,//受众
                expires: DateTime.Now.AddDays(1), //过期时间， 一天后过期
                signingCredentials: signingCredentials,
                claims: claims
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }

        /// <summary>
        /// 解析Token令牌
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpGet("GetTokenClaim")]
        [AllowAnonymous]
        public async Task<UserDto> GetTokenClaim(string token)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            var payload = jwtHandler.ReadJwtToken(token).Payload;
            var claims = payload.Claims;
            var userId = claims.Where(x => x.Type == "UserId").FirstOrDefault();
            var userName = claims.Where(x => x.Type == "UserName").FirstOrDefault();
            var phone = claims.Where(x => x.Type == "Phone").FirstOrDefault();
            var result = new UserDto()
            {
                UserId = int.Parse(userId.Value),
                UserName = userName.Value,
                Phone = phone.Value
            };
            return result;
        }


        /// <summary>
        /// 修改权限
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPut("PutPermission")]
        public async Task<Result> PutPermission(PermissionUpdateCommand cmd)
        {
            try
            {
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {

                throw;
            }
        }

        [HttpPost("PostRoleAdd")]
        public async Task<Result> Handle(RoleCreateCommand request)
        {
            return await mediator.Send(request);

        }
        [HttpPut("PutDelete")]
        public async Task<Result> Handle(PermissionDelCommand request)
        {
            return await mediator.Send(request);
        }

        /// <summary>
        /// 角色显示查询
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("PostRoleList")]
        public async Task<Result> Handle(RoleListCommand request)
        {
            return await mediator.Send(request);
        }

        /// <summary>
        /// 用户添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// 
        [HttpPost("PostUserAdd")]
        public async Task<Result> Handle(UserCreateCommand request)
        {
            return await mediator.Send(request);
        }

        [HttpPost("PsotUserList")]
        public async Task<Result> Handle(UserListCommand request)
        {
            return await mediator.Send(request);
        }

        [HttpPost("PermissionFill")]
        public async Task<List<Permission>> Handle(PermissionFillCommand request)
        {
            return await mediator.Send(request);
        }

        /// <summary>
        /// 角色删除
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPut("DelRoleList")]
        public async Task<Result> Handle(RoleDelCommand request)
        {
            return await mediator.Send(request);
        }


        [HttpPost("Login")]
        [AllowAnonymous]
        public async Task<Result> Handle(UserLoginCommand request)
        {

            request.token = CreateTokenString(request.UserName);
            return await mediator.Send(request);
        }
        [HttpPost("GetCHeckRole")]
        public async Task<Result> Handle(RoleCheckCommand request)
        {
          return await mediator.Send(request);
        }
        [HttpPut("PutUSerDelete")]
        public async Task<Result> Handle(UserDelCommand request)
        {
            return await mediator.Send(request);
        }

        [HttpPost("UserPermission")]
        public async Task<Result> Handle(MainPermissionCommand request)
        {
           return await mediator.Send(request);
        }
    }

}
